const axios = require('axios');
const cheerio = require('cheerio');
const path = require('path');

// 定义要爬取的URL
const url = 'https://auto.16888.com';
let res = []
class Brand {
    constructor(name) {
        this.name = name;
        this.id = '';
        this.childBrands = [];
    }
    addChildBrand(childBrand) {
        this.childBrands.push(childBrand);
    }
}

class Car {
    constructor({ name, brandName, id }) {
        this.name = name;
        this.brandName = brandName;
        this.id = id;
    }
}

axios.get(url)
    .then(response => {
        if (response.status === 200) {
            const html = response.data;
            const $ = cheerio.load(html);
            const $title = $('.brand_box');
            $title.each((index, brand) => {
                const $brandName = $(brand).children('a');
                const $childBrands = $(brand).find('.brand_list').children('ul').children('li').children('span').children('a').not('.f_h');
                $childBrands.each((index, childBrand) => {
                    const name = $(childBrand).attr('title');

                    const href = $(childBrand).attr('href');
                    const id = href.split('/')[3]
                    if (name && id) {
                        const car = new Car({ name, brandName: $brandName.attr('name'), id });
                        res.push(car);
                    }

                })
            })

            console.log(res)
            const json = { data: res };
            // 保存到当前目录/car.json中
            const fs = require('fs');
            fs.writeFileSync(path.join(__dirname, 'car.json'), JSON.stringify(json, null, 2));
        }
    })
    .catch(error => {
        console.error(`Error fetching the URL: ${error.message}`);
    });
